package com.parleys.service;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import com.google.inject.Singleton;
import com.parleys.service.intf.ParleysHTTPClient;

@Singleton
public class ParleysHTTPClientImpl implements ParleysHTTPClient {

	private static final String HTTP = "http";
	private static final String DEFAULT_ENCODING = "ISO-8859-1";

	private static final HttpClient HTTP_CLIENT;

	static {
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, DEFAULT_ENCODING);
		params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 5);
		final SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme(HTTP, PlainSocketFactory.getSocketFactory(), 80));
		ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
		HTTP_CLIENT = new DefaultHttpClient(manager, params);
	}

	public String getContentAsString(final String url) throws IOException {

		Reader reader = null;
		final HttpEntity entity = getContent(url);

		if (entity != null) {

			// using the response encoding when available
			if (entity.getContentEncoding() != null) {
				reader = new InputStreamReader(entity.getContent(), entity.getContentEncoding().getValue());
			} else {
				reader = new InputStreamReader(entity.getContent(), DEFAULT_ENCODING);
			}
		} else {
			throw new IOException("Response of http request is empty");
		}

		return IOUtils.toString(reader);
	}

	public HttpEntity getContent(final String url) throws IOException {
		HttpGet httpget = new HttpGet(url);
		HttpResponse httpResponse = HTTP_CLIENT.execute(httpget);

		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return httpResponse.getEntity();
		} else {
			throw new IOException("Http request did not return code 200");
		}
	}

}
